package com.gec.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

//@WebFilter(urlPatterns = { "/Common/index", "/User/*" ,"/Notify/*",
//		"/Room/*","/RoomType/*","/Storey/*","/Option/*"})
public class LoginFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest _req = (HttpServletRequest) req;
		HttpServletResponse _resp = (HttpServletResponse) resp;
		// {1}先得到 session(true)
		HttpSession session = _req.getSession();
		// {2}从 session 取出名为 "user" 的域数据。
		Object user = session.getAttribute("user");
		// {3}判断是否存在 user.
		if (user != null) { // 我已经登录过了。
			// {4}登录过(存在则--->放行。)
			chain.doFilter(req, resp);
			// {5}这里一定要 return.
			return;
		}
		String ctxPath = _req.getContextPath();
		// {1}为什么要对 msg 进行编码 ?
		String msg = URLEncoder.encode("不好意思, 你没有登录。", "UTF-8");
		// {5}不存在重定向到: login.jsp?msg=没有登录
		_resp.sendRedirect(ctxPath + "/Common/showLogin?msg=" + msg);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}
}
